package com.lonty.intelligence.service;

import com.lonty.intelligence.mapper.SystemNotificationMapper;
import com.lonty.intelligence.mapper.SystemNotificationUserMapper;
import com.lonty.intelligence.mapper.UserInfoMapper;
import com.lonty.intelligence.model.SystemNotification;
import com.lonty.intelligence.request.SystemNotificationList;
import com.lonty.intelligence.util.UUIDUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @Author 陈璇
 * @Date 2020/5/28 10:16
 * @Version 1.0
 */
@Service
public class SystemNotificationService {

    @Resource
    private SystemNotificationMapper systemNotificationMapper;

    @Resource
    private UserInfoMapper userInfoMapper;

    @Resource
    private SystemNotificationUserMapper systemNotificationUserMapper;

    /**
     * 保存系统通知
     * @param content
     * @return
     */
    @Transactional
    public boolean saveSystemNotification(String content){
        //保存系统通知
        SystemNotification systemNotification = new SystemNotification();
        systemNotification.setId(UUIDUtil.randomID());
        systemNotification.setContent(content);
        systemNotification.setCreateTime(LocalDateTime.now());
        systemNotificationMapper.saveSystemNotification(systemNotification);
        //获取所有用户ID
        String id = userInfoMapper.getAllUserId();
        String[] ids = id.split(",");
        //保存系统通知接收人
        if(systemNotificationUserMapper.saveBatchSystemNotificationUser(ids, systemNotification.getId()) > 0){
            return true;
        }
        return false;
    }

    /**
     * 获取用户所有通知
     * @param userInfoId
     * @return
     */
    public List<SystemNotificationList> getAllSystemNotificationList(String userInfoId){
        return systemNotificationUserMapper.getAllSystemNotificationList(userInfoId);
    }

    /**
     * 统计用户未读
     * @param userInfoId
     * @return
     */
    public int countUnread(String userInfoId){
        return systemNotificationUserMapper.countUnread(userInfoId);
    }

    /**
     * 获取通知详情
     * @param id
     * @return
     */
    @Transactional
    public SystemNotification getSystemNotification(String id, String userInfoId){
        //修改通知状态
        systemNotificationUserMapper.modifyStatus(userInfoId, id);
        return systemNotificationMapper.getSystemNotification(id);
    }

}
